package william.list;

/**
 * @author ZhangShenao
 * @date 2024/3/10
 * @description <a href="https://leetcode.cn/problems/add-two-numbers/">...</a>
 */
public class Leetcode2_两数相加 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 同时遍历两个链表,将相应的节点相加,创建新的节点,追加到新链表末尾
     * 需要特别处理进位的情况
     * <p>
     * 时间复杂度O(N) 两个链表各遍历一遍
     * 空间复杂度O(1)
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //边界条件校验
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        //借助哑头节点
        ListNode dummy = new ListNode();
        ListNode cur = dummy;

        //记录进位
        int carry = 0;

        //同时遍历两个链表,将对应的节点相加
        while (l1 != null || l2 != null || carry > 0) {
            //将两节点相加
            int sum = 0;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }

            //进位相加
            sum += carry;

            //创建新节点
            cur.next = new ListNode(sum % 10);
            cur = cur.next;

            //更新进位
            carry = sum / 10;

        }


        //返回新链表的头结点
        return dummy.next;
    }
}
